from flask import Blueprint, request
from exts import db
from models import Today_in_history

import Crawler_data.Today_crawler as Today_crawler
import threading

bp = Blueprint("Today", __name__, url_prefix="/Today")

# 写入数据接口
# T_year
# incident
# month

@bp.route("/Event/write",methods=['POST'])
def Event_write():
    if request.method == "POST":
        if request.content_type.startswith('application/json'):
            T_year = request.json.get('T_year')
            incident = request.json.get('incident')
            month = request.json.get('month')
        elif request.content_type.startswith('multipart/form-data'):
            T_year = request.form.get('T_year')
            incident = request.form.get('incident')
            month = request.form.get('month')
        else:
            T_year = request.values.get("T_year")
            incident = request.values.get("incident")
            month = request.values.get("month")
        Today_add=Today_in_history(T_year=T_year,incident=incident,T_month=month)
        db.session.add(Today_add)
        #这个为添加数据到暂存区
        db.session.commit()
        # #这个为把暂存区的数据提交到数据库中去
    return "正在写入"



# 读取接口      month:月             day:日
@bp.route("/Event/read",methods=['GET'])
def Event_read():
    # month:月
    month=request.values.get("month")
    day=request.values.get("day")
    if month is None:
        return {
            "code":"404",
            "errno":"请检查参数"
        }
    elif day is None:
        return {
            "code":"404",
            "errno":"请检查参数"
        }
    else:
        T_month="{0}-{1}".format(month, day)
        data = Today_in_history.query.filter_by(T_month=T_month).all()
        if data == []:
            # 执行的时候
            # Today_crawler.main()
            t = threading.Thread(target=Today_crawler_main)
            t.start()
            t.join()
            print("执行数据结束，获取数据")
            data = Today_in_history.query.filter_by(T_month=T_month).all()
            # 在这里还是获取错误
            # 在这里查询还是为空，数据好像并未添加成功
        T_data=[]
        for item in data:
            T_data.append({
                "id": item.Tid,
                "year": item.T_year,
                "incident": item.incident,
                "T_month": item.T_month
            })
                    # 直接获取全部符合条件的数据
        return {"code": "200", "data": T_data,"Current":T_month}



def Today_crawler_main():
    print("开始执行")
    Today_crawler.main()
    print("执行完成")
